//
//  UserCenterViewController.m
//  xpkc
//
//  Created by TopSageMacMini on 14/12/18.
//  Copyright (c) 2014年 wanmeizty. All rights reserved.
//

#import "UserCenterViewController.h"
#import "GZRStrecthScrollView.h"
#import "Masonry.h"
#import "UserMessage.h"
#import "UserSettingViewController.h"
#import "FeedbackViewController.h"
#import "MyNotificationViewController.h"
#import "CourseViewController.h"
#import "LoginViewController.h"
#import "OrderViewController.h"
#import "CourseCenterCartViewController.h"
#import "DeliveryAddressViewController.h"
#import "Q&AViewController.h"
#import "MyRemindViewController.h"
#import "ActivityViewController.h"
#import "PersonShowVC.h"
#import "OffLineViewController.h"
#import "CourseCenterCartViewController.h"
#import "UIImageView+AFNetworking.h"
#import "StudyCardViewController.h"

@interface UserCenterViewController () <UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    UserCenterView *userView;
    NSInteger msgNum;
    NSInteger actNum;
    NSInteger qesNum;
    
}
@end

@implementation UserCenterViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if(self) {
        self.tabBarItem.image = [UIImage imageNamed:@"tab_my"];
        if (IsIOS7) {
            self.tabBarItem.title = @"我";
            self.tabBarItem.selectedImage = [[UIImage imageNamed:@"tab_my_selected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        }
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    
    [[UIDevice currentDevice]
     setValue:[NSNumber
               numberWithInteger:UIInterfaceOrientationPortrait]
     forKey:@"orientation"];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self checkIsLogin];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    [self creatUserCenterView];
}

- (void)creatNavigationItem{
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    [self.navigationController.navigationBar setBackgroundColor:CCOLOR];
}

- (void)creatUserCenterView{
    NSArray *menus = @[@"我的课程",@"离线管理",@"",
                       @"全部订单",@"学习卡",@"我的购物车",@"我的收货地址",@"",
                       @"我的消息",@"我的答疑",@"",
                       @"最新优惠活动"];
    NSArray *icons = @[@"my_mycourse",@"my_offline",@"",
                       @"my_myorder",@"my_studycard",@"my_shopcar",@"my_address",@"",
                       @"my_msg",@"my_quest",@"",
                       @"my_action"];
    
    userView = [[UserCenterView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 40)];
    userView.delegate = self;
    [userView menuTitles:menus andIcons:icons];
    [self.view addSubview:userView];
}

- (void)checkIsLogin{
    if (userView.isLogin) {
         [self getMessages];
        return;
    }else{
        if ([UserMessage sharedUserMessage].isLogin) {
            
           
            
            NSURL *headurl = [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] valueForKey:USERHEAD_REMBER]];
            logdebug(@"%@",headurl);
            NSString *username = [[NSUserDefaults standardUserDefaults]valueForKey:USERNAME_REMBER];
            [userView.header.buttonImage setImageWithURL:headurl placeholderImage:[UIImage imageNamed:@"portrait"]];
            userView.header.buttonTitle.text = username;
            userView.isLogin = YES;
        }
    }
}

#pragma mark - usercenterview delegate
- (void)menuBtnClick:(UIButton *)btn{
    switch (btn.tag) {
        case 0:
        {
            self.tabBarController.selectedIndex = 3;
        }
            break;
        case 1:
        {
            OffLineViewController *OLMV = [[OffLineViewController alloc]init];
            OLMV.hidesBottomBarWhenPushed = YES;
            if (IsIOS7) {
                if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
                    self.navigationController.interactivePopGestureRecognizer.delegate = nil;
                }
            }
            [self.navigationController setNavigationBarHidden:NO animated:NO];
            [self.navigationController pushViewController:OLMV animated:YES];
            
        }
            break;
        case 3:
        {
            if (![UserMessage sharedUserMessage].isLogin) {
                [self showAlertWithMessage:@"请先登陆"];
            }else{
                OrderViewController *OVC = [[OrderViewController alloc]init];
                OVC.hidesBottomBarWhenPushed = YES;
                if (IsIOS7) {
                    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
                        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
                    }
                }
                [self.navigationController setNavigationBarHidden:NO animated:NO];
                [self.navigationController pushViewController:OVC animated:YES];
            }
        }
            break;
        case 4:
        {
            logdebug(@"学习卡");
            if (![UserMessage sharedUserMessage].isLogin) {
                [self showAlertWithMessage:@"请先登陆"];
            }else{
                
                StudyCardViewController * studyCard = [[StudyCardViewController alloc] init];
                
                studyCard.hidesBottomBarWhenPushed = YES;
                
                if (IsIOS7) {
                    
                    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
                        
                        
                        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
                    }
                    
                }
                [self.navigationController setNavigationBarHidden:NO animated:NO];
                [self.navigationController pushViewController:studyCard animated:YES];
                
            }
        }
            break;
        case 5:
        {
            logdebug(@"购物车");
            if (![UserMessage sharedUserMessage].isLogin) {
                [self showAlertWithMessage:@"请先登陆"];
            }else{
                CourseCenterCartViewController *CCCVC = [[CourseCenterCartViewController alloc]init];
                CCCVC.hidesBottomBarWhenPushed = YES;
                if (IsIOS7) {
                    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
                        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
                    }
                }
                [self.navigationController setNavigationBarHidden:NO animated:NO];
                [self.navigationController pushViewController:CCCVC animated:YES];
            }
        }
            break;
        case 6:
        {
            if (![UserMessage sharedUserMessage].isLogin) {
                [self showAlertWithMessage:@"请先登陆"];
            }else{
                DeliveryAddressViewController *DAVC = [[DeliveryAddressViewController alloc]init];
                DAVC.hidesBottomBarWhenPushed = YES;
                if (IsIOS7) {
                    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
                        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
                    }
                }
                [self.navigationController setNavigationBarHidden:NO animated:NO];
                [self.navigationController pushViewController:DAVC animated:YES];
            }
        }
            break;
        case 8:
        {
            if (![UserMessage sharedUserMessage].isLogin) {
                [self showAlertWithMessage:@"请先登陆"];
            }else{
                MyNotificationViewController *MNVC = [[MyNotificationViewController alloc]init];
                MNVC.hidesBottomBarWhenPushed = YES;
                if (IsIOS7) {
                    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
                        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
                    }
                }
                [self.navigationController setNavigationBarHidden:NO animated:NO];
                [self.navigationController pushViewController:MNVC animated:YES];
            }
        }
            break;
        case 9:
        {
            if (![UserMessage sharedUserMessage].isLogin) {
                [self showAlertWithMessage:@"请先登陆"];
            }else{
                Q_AViewController *QAVC = [[Q_AViewController alloc]init];
                QAVC.hidesBottomBarWhenPushed = YES;
                if (IsIOS7) {
                    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
                        self.navigationController.interactivePopGestureRecognizer.delegate = nil;
                    }
                }
                [self.navigationController setNavigationBarHidden:NO animated:NO];
                [self.navigationController pushViewController:QAVC animated:YES];
            }
        }
            break;
        case 11:
        {
            ActivityViewController *AVC = [[ActivityViewController alloc]init];
            AVC.hidesBottomBarWhenPushed = YES;
            if (IsIOS7) {
                if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
                    self.navigationController.interactivePopGestureRecognizer.delegate = nil;
                }
            }
            [self.navigationController setNavigationBarHidden:NO animated:NO];
            [self.navigationController pushViewController:AVC animated:YES];
        }
            break;
            
        default:
            break;
    }
}

- (void)userHeadClick:(UIButton *)btn{
    if ([UserMessage sharedUserMessage].isLogin) {
        logdebug(@"已登录，更换头像");
        //        UIActionSheet *sheetView = [[UIActionSheet alloc] initWithTitle:@"选择照片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相机",@"相册", nil];
        //        [sheetView showInView:self.view];
        
        PersonShowVC * person = [[PersonShowVC alloc]init];
        person.hidesBottomBarWhenPushed = YES;
        // UINavigationController * nv = [[UINavigationController alloc]initWithRootViewController:person];
        [self.navigationController setNavigationBarHidden:NO animated:NO];
        [self.navigationController pushViewController:person animated:YES];
        
        
        
        
        
        
    }else{
        logdebug(@"未登录，登录");
        LoginViewController *LVC = [[LoginViewController alloc]init];
        LVC.loginBlock = ^(NSString *username,NSString *headimg){
            [userView.header.buttonImage setImageWithURL:[NSURL URLWithString:headimg] placeholderImage:[UIImage imageNamed:@"portrait"]];
            userView.header.buttonTitle.text = username;
            userView.isLogin = YES;
        };
        LVC.hidesBottomBarWhenPushed = YES;
        if (IsIOS7) {
            if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
                self.navigationController.interactivePopGestureRecognizer.delegate = nil;
            }
        }
        [self.navigationController setNavigationBarHidden:NO animated:NO];
        [self.navigationController pushViewController:LVC animated:YES];
    }
}

- (void)signOutBtnClick:(UIButton *)btn{
    userView.isLogin = NO;
    [UserMessage sharedUserMessage].isLogin = NO;
    msgNum = 0;
    actNum = 0;
    qesNum = 0;
    [self checkBadgevelue];
}

- (void)setBtnClick:(UIButton *)btn{
    UserSettingViewController *USV = [[UserSettingViewController alloc]init];
    USV.title = @"设置";
    USV.hidesBottomBarWhenPushed = YES;
    if (IsIOS7) {
        if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
            self.navigationController.interactivePopGestureRecognizer.delegate = nil;
        }
    }
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    [self.navigationController pushViewController:USV animated:YES];
}

#pragma mark - func

- (void)getMessages{
    
    
        msgNum=0;
        NSString *module = @"user";
        NSString *interface = @"allmsg";
        NSString *timeString = [GetTime getTime];
        NSString *hashString = [[NSString stringWithFormat:@"%@/%@/key/%@/time/%@",module,interface,KEY,timeString] md5];
        NSString *urlString = [NSString stringWithFormat:@"%@/laravel/public/%@/%@/hash/%@/appid/1",URL2,module,interface,hashString];
        NSDictionary *paramtes = [NSDictionary dictionaryWithObjectsAndKeys:timeString,@"time",[UserMessage sharedUserMessage].userMid,@"userid",@0,@"pagecode",nil];
       AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
       manager.responseSerializer = [AFHTTPResponseSerializer serializer];
      [manager POST:urlString parameters:paramtes success:^(AFHTTPRequestOperation *operation, id responseObject) {
       NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        
        if ([[dic objectForKey:@"info"] isKindOfClass:[NSString class]]) {
            msgNum=0;
            self.tabBarItem.image = [UIImage imageNamed:@"set"];
            if (IsIOS7) {
                self.tabBarItem.selectedImage = [[UIImage imageNamed:@"tab_my_selected@2x"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        }

        }else{
        NSArray * infoArray = [dic objectForKey:@"info"];
        for (NSDictionary * infoDic in infoArray) {
    if ([[infoDic objectForKey:@"is_view"] isEqualToNumber:@0]) {
                    msgNum++;
        }
             
                }
            
             [self checkBadgevelue];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       

    }];
   
   
}
- (void)getActivities{
    //TODO:请求活动内容
    [self checkBadgevelue];
}
- (void)getQuestions{
    //TODO:请求答疑内容
    [self checkBadgevelue];
}

/**
 *  检查消息数
 */
- (void)checkBadgevelue{
    BOOL show = NO;
    if (msgNum > 0) {//8
        show = YES;
        [userView updateBtnAtIndex:8 withBadgevalue:[NSString stringWithFormat:@"%ld",(long)msgNum]];
    }else{
        [userView updateBtnAtIndex:8 withBadgevalue:@""];
    }
    if (actNum > 0) {//11
        show = YES;
        [userView updateBtnAtIndex:11 withBadgevalue:[NSString stringWithFormat:@"%ld",(long)msgNum]];
    }else{
        [userView updateBtnAtIndex:11 withBadgevalue:@""];
    }
    if (qesNum > 0) {//9
        show = YES;
        [userView updateBtnAtIndex:9 withBadgevalue:[NSString stringWithFormat:@"%ld",(long)msgNum]];
    }else{
        [userView updateBtnAtIndex:9 withBadgevalue:@""];
    }
    
    if (!show) {
        self.tabBarItem.image = [UIImage imageNamed:@"tab_my"];
        if (IsIOS7) {
            self.tabBarItem.selectedImage = [[UIImage imageNamed:@"tab_my_selected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        }
    }else{
        self.tabBarItem.image = [[UIImage imageNamed:@"tab_my_red"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        if (IsIOS7) {
            self.tabBarItem.selectedImage = [[UIImage imageNamed:@"tab_my_selected_red"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        }
    }
}

//#pragma mark - 更换头像相关代理
//- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
//    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
//    
//    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
//        //取到图片
//        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
//        userView.header.buttonImage.image = image;
//        // 压缩获取到的图片 压缩数据需要上传到服务器
//        //TODO:头像上传
////        NSData *imageData = UIImageJPEGRepresentation(image, 0.01);
//    }
//    
//    [self dismissViewControllerAnimated:YES completion:nil];
//}

//- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
//    [self dismissViewControllerAnimated:YES completion:nil];
//}

//- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
//    if(buttonIndex != 2) {
//        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
//        picker.delegate = self;
//        picker.allowsEditing = YES;
//        
//        if(buttonIndex == 1) {   // 相册
//            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
//                picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//                [self presentViewController:picker animated:YES completion:^{
//                    
//                }];
//            }else{
//                [self showAlertWithMessage:@"无法调用相册库"];
//            }
//        } else if(buttonIndex ==0 ){
//            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
//                picker.sourceType = UIImagePickerControllerSourceTypeCamera;
//                [self presentViewController:picker animated:YES completion:^{
//                    
//                }];
//            }else{
//                [self showAlertWithMessage:@"相机不可用"];
//            }
//        }
//    }
//}

- (void)showAlertWithMessage:(NSString *)message {
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alertView show];
}

#pragma mark - other

- (BOOL)shouldAutorotate{
    return NO;
}
- (NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
